//
//  ViewController.m
//  音频的录制与播放
//
//  Created by 梁森 on 2018/5/20.
//  Copyright © 2018年 梁森. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
@interface ViewController ()

@property (nonatomic, strong) AVAudioRecorder * recorder;
@property (nonatomic, strong) AVAudioPlayer * player;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}
// 录音
- (IBAction)record:(id)sender {
    UIButton * btn = (UIButton *)sender;
    
    if (btn.selected == NO) {
        NSLog(@"开始录音...");
        [self.recorder record];
    }else{
        NSLog(@"结束录音...");
        [self.recorder stop];
    }
    
    btn.selected = !btn.selected;
}
// 播放录音
- (IBAction)play:(id)sender {
    UIButton * btn = (UIButton *)sender;
    
    if (btn.selected == NO) {
        NSLog(@"开始播放...");
        [self.player play];
    }else{
        NSLog(@"结束播放...A");
        [self.player stop];
    }
    
    btn.selected = !btn.selected;
}
// 懒加载
- (AVAudioRecorder *)recorder{
    if (_recorder == nil) {
        // 录音保存路径
        NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/record"];
        NSMutableDictionary * settings = [NSMutableDictionary dictionary];
        // 采样率
        settings[AVSampleRateKey] = [NSNumber numberWithInt:44100];
        // 录音格式
        settings[AVFormatIDKey] = [NSNumber numberWithInt:kAudioFormatMPEG4AAC];
        // 录音通道
        settings[AVNumberOfChannelsKey] = [NSNumber numberWithInt:1];
        // 录音质量
        settings[AVEncoderAudioQualityKey] = [NSNumber numberWithInt:AVAudioQualityMax];  // 高质量
        _recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL URLWithString:path] settings:settings error:nil];
        [_recorder prepareToRecord];
    }
    return _recorder;
}
- (AVAudioPlayer *)player{
    if (_player == nil) {
        // 录音路径
        NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/record"];
        // 既可以播放网络的也可以播放本地的
        _player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:path] error:nil];
        [_player prepareToPlay];
    }
    return _player;
}


@end
